package com.jinlia.show.modules.base.system.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinlia.show.modules.base.model.po.GoodsPO;
import com.jinlia.show.modules.base.system.entity.GoodsAttr;
import com.jinlia.show.modules.base.system.entity.GoodsAttrValue;
import com.jinlia.show.modules.base.system.mapper.GoodsAttrMapper;
import com.jinlia.show.modules.base.model.po.GoodsAttrPO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class GoodsAttrMapperService extends ServiceImpl<GoodsAttrMapper, GoodsAttr> {

    @Autowired
    private GoodsAttrValueMapperService goodsAttrValueMapperService;

    public List<GoodsAttrPO> getPOsByGoodsId(Long... goodsId) {
        List<GoodsAttrPO> pOsByGoodsIds = this.baseMapper.getPOsByGoodsIds(Arrays.asList(goodsId));
        return pOsByGoodsIds;
    }

    public void fillGoods(List<GoodsPO> list){
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        List<GoodsAttrPO> pOsByGoodsIds = this.baseMapper.getPOsByGoodsIds(list.stream().map(GoodsPO::getId).collect(Collectors.toList()));
        Map<Long, List<GoodsAttrPO>> collect = pOsByGoodsIds.stream().collect(Collectors.groupingBy(GoodsAttrPO::getGoodsId));
        for (GoodsPO goodsPO : list) {
            if (collect.containsKey(goodsPO.getId())) {
                goodsPO.setGoodsAttrPOS(collect.get(goodsPO.getId()));
            }
        }
    }
    /**
     * 获取商品属性
     *
     * @param skuItem
     * @return
     */

    public String buildSkuName(JSONObject skuItem) {
        if (CollectionUtils.isEmpty(skuItem.keySet())) {
            return "";
        }
        Map<Long, String> collectGoodsAttr = this.lambdaQuery()
                .in(GoodsAttr::getId, skuItem.keySet())//属性
                .list()
                .stream()
                .collect(Collectors.toMap(GoodsAttr::getId, GoodsAttr::getAttrName));
        Map<Long, String> collectGoodsAttrValue = goodsAttrValueMapperService.lambdaQuery()
                .in(GoodsAttrValue::getId, skuItem.values())//属性值
                .list()
                .stream()
                .collect(Collectors.toMap(GoodsAttrValue::getId, GoodsAttrValue::getAttrValueName));
        StringBuilder pOsByGoodsIds = new StringBuilder();
        skuItem.keySet().stream().sorted().forEach(key -> {//  排序后构造
            pOsByGoodsIds.append(collectGoodsAttr.get(Long.valueOf(key))).append(":").append(collectGoodsAttrValue.get(Long.valueOf(skuItem.get(key).toString())));

        });
        return pOsByGoodsIds.toString();
    }
}
